package com.bole.controller;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.bole.config.AlipayConfig;
import com.bole.data.Result;
import com.bole.data.ResultEnum;
import com.bole.dto.car.EsCar;
import com.bole.dto.car.TbCarDto;
import com.bole.dto.order.TbOrderDto;
import com.bole.dto.order.TbPayLogDto;
import com.bole.dto.user.UserDto;

import com.bole.feign.CarFeign;
import com.bole.feign.OrderFeign;
import com.bole.feign.PayLogFeign;
import com.bole.feign.reception.EsFeign;
import com.bole.feign.reception.UserServiceFeign;
import com.bole.util.IdWorker;

import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.annotations.ApiImplicitParam;

import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.rest.RestStatus;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;
import java.text.ParseException;


@CrossOrigin
@Controller
@RequestMapping("order")
public class OrderController {

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private PayLogFeign payLogFeign;

    @Autowired
    private AlipayConfig alipayConfig;

    @Autowired
    private CarFeign carFeign;

    @Autowired
    private UserServiceFeign userServiceFeign;

    @Autowired
    private EsFeign esFeign;

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    //买家id
    Long buyId = (long) 0;

    //卖家id
    Long sellId = (long) 0;



    @RequestMapping("addOrder")
    @ResponseBody
    @ApiImplicitParam(name = "carId", value = "carId", required = true, dataTypeClass = Long.class)
    public Result addOrder( @RequestParam("cookie")String cookie,HttpServletRequest request, HttpServletResponse response, @RequestParam("carId") Long carId) throws IOException {
        //获取用户登录信息
       /* UserDto user = (UserDto) SecurityUtils.getSubject().getPrincipal();
        if (user == null || "".equals(user)){
            return  Result.response(ResultEnum.FAIL).setData("未登录");
        }*/
        //通过手机号查询一下用户id
        UserDto user = userServiceFeign.getUserByTelePhone(cookie);
        //获取到买家id
        buyId = user.getId();
        //修改es 状态

        //获取买家手机号
        TbOrderDto order = new TbOrderDto();
        order.setBuyUserId(buyId);
        order.setBuyTelephone(user.getTelephone());
        carFeign.updateStutsCar(carId);
        esFeign.updateStatus(carId);
        TbOrderDto orderdto = orderFeign.saveOrder(carId, order);
        return Result.response(ResultEnum.OK).setData(orderdto);
    }

    /**
     * @param out_trade_no 商户订单号，商户网站订单系统中唯一订单号，必填
     * @param subject      订单名称，必填
     * @param total_amount 付款金额，必填
     * @param body         商品描述，可空
     * @return
     */
    @RequestMapping("goPay")
    @ResponseBody
    public String goPay(String out_trade_no, String subject, String total_amount, String body) {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getApp_id(),
                alipayConfig.getMerchant_private_key(), alipayConfig.getFormate(), alipayConfig.getCharset(),
                alipayConfig.getAlipay_public_key(), alipayConfig.getSign_type());

        //创建支付交易的对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        //设置请求参数
        alipayRequest.setReturnUrl(alipayConfig.getReturn_url());
        alipayRequest.setNotifyUrl(alipayConfig.getNotify_url());

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
        //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
        //		+ "\"total_amount\":\""+ total_amount +"\","
        //		+ "\"subject\":\""+ subject +"\","
        //		+ "\"body\":\""+ body +"\","
        //		+ "\"timeout_express\":\"10m\","
        //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.order-请求参数】章节

        //请求
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //输出
        return result;
    }

    /**
     * 同步回调地址
     * 不能在此方法中修改订单状态为已支付 因为此方法仅仅是从支付宝网站提回来的方法 不能当做校验支付是否成功的逻辑
     *
     * @return
     */
    @RequestMapping("return_url")
    public String return_url(HttpServletRequest request, String out_trade_no, String trade_no, String total_amount, Model model) throws Exception {
        System.out.println(">>>>>>>>>> 进入同步回调 <<<<<<<<<<");
        //获取支付宝GET过来反馈信息
//        Map<String,String> params = new HashMap<String,String>();
//        //通过request获取所有的参数
//        Map<String,String[]> requestParams = request.getParameterMap();
//        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
//            String name = (String) iter.next();
//            String[] values = (String[]) requestParams.get(name);
//            String valueStr = "";
//            for (int i = 0; i < values.length; i++) {
//                valueStr = (i == values.length - 1) ? valueStr + values[i]
//                        : valueStr + values[i] + ",";
//            }
//            //乱码解决，这段代码在出现乱码时使用
////            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
//            params.put(name, valueStr);
//        }
//
//        boolean signVerified = AlipaySignature.rsaCheckV1(params,
//               alipayConfig.getAlipay_public_key(), alipayConfig.getCharset(), alipayConfig.getSign_type()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if (true) {
            //商户订单号
            System.out.println("商户订单号：" + out_trade_no);
            //支付宝交易号
            System.out.println("支付宝交易号:" + trade_no);
            //付款金额
            System.out.println("付款金额：" + total_amount);
            model.addAttribute("out_trade_no", out_trade_no);
            model.addAttribute("trade_no", trade_no);
            model.addAttribute("total_amount", total_amount);
            //编写业务
            return "paysuccess";
        } else {
            model.addAttribute("msg", "验签失败");
            return "payfail";
        }
    }

    /**
     * 异步回调地址
     * 在此方法中修改订单为已支付(如果是支付成功) 区分退款使用out_biz_no参数
     *
     * @return
     */
    @RequestMapping("notify_url")
    @ResponseBody
    public String notify_url(String out_trade_no, String trade_no, String total_amount, String trade_status, String gmt_create, String gmt_payment, String out_biz_no, HttpServletRequest request) throws AlipayApiException, ParseException {
        System.out.println(">>>>>>>>>> 进入异步回调 <<<<<<<<<<");
        /* *
         *************************页面功能说明*************************
         * 创建该页面文件时，请留心该页面文件中无任何HTML代码及空格。
         * 该页面不能在本机电脑测试，请到服务器上做测试。请确保外部可以访问该页面。
         * 如果没有收到该页面返回的 success 支付宝会继续回调我们(重试) 但是会有时间间隔 间隔越来越长
         * 建议该页面只做支付成功的业务逻辑处理，退款的处理请以调用退款查询接口的结果为准。
         */

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        //获取所有的参数
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params,
                alipayConfig.getAlipay_public_key(), alipayConfig.getCharset(), alipayConfig.getSign_type()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

        /* 实际验证过程建议商户务必添加以下校验：
        1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
        2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
        3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
        4、验证app_id是否为该商户本身。
        */
        if (signVerified) {//验证成功
            //校验 订单id 支付金额 商家是否和付款保持一致，避免被人篡改信息
            //商户订单号
            System.out.println("商户订单号：" + out_trade_no);
            //支付宝交易号
            System.out.println("支付宝交易号:" + trade_no);
            //交易状态
            System.out.println("交易状态:" + trade_status);
            System.out.println("创建时间" + gmt_create);
            System.out.println("支付时间" + gmt_payment);
            System.out.println("金额" + total_amount);
            if (out_biz_no != null || "".equals(out_biz_no)) {
                System.out.println("退款成功");
                return "success";
            }
            //更新paylog和order中状态；清除redis中母订单；调用积分模块等
            //查询订单表

            TbPayLogDto payLog = new TbPayLogDto();
            //卖家id
            //买家id
            payLog.setOutTradeNo(out_trade_no);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            BigDecimal price = new BigDecimal(total_amount);
            payLog.setTotalFee(price);
            payLog.setCreateTime(simpleDateFormat.parse(gmt_create));
            payLog.setPayTime(simpleDateFormat.parse(gmt_payment));
            payLog.setTransactionId(trade_no);
            payLog.setTradeState("2");//已付款
            payLog.setPayType("1");
            payLog.setBuyUserId(buyId);

            //更新订单表
            //修改支付表支付状态
            //把订单号加上
            TbOrderDto orderDto = orderFeign.selectById(Long.parseLong(out_trade_no));
            sellId = orderDto.getSellUserId();
            orderDto.setId( Long.parseLong(out_trade_no));
            orderDto.setPayTime(simpleDateFormat.parse(gmt_payment));
            orderDto.setStatus("1");
            orderDto.setOutTradeNo(trade_no);
            orderFeign.updateOrder(orderDto);
            payLog.setSellUserId(sellId);





//            redisTemplate.delete(userName+out_trade_no);
            if (trade_status.equals("TRADE_FINISHED")) { //交易关闭
                //判断该笔订单是否在商户网站中已经做过处理 保证幂等性
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序
                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            } else if (trade_status.equals("TRADE_SUCCESS")) {
                //此代码块真正告诉我们付款成功
                //判断该笔订单是否在商户网站中已经做过处理 保证幂等性
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //清除redis中母订单
//                redisTemplate.delete(user.getUsername()+out_trade_no);
                payLogFeign.savePayLog(payLog);
                orderFeign.updateOrder(orderDto);
                // 更新paylog和order中状态
                //增加积分
//                rocketMQTemplate.convertAndSend("sale",userName+","+id+","+total_amount);

                //如果有做过处理，不执行商户的业务程序
                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            //同时将支付交易号更新到order表中多个order数据(同一母订单）。
//            orderService.updateAlipayOrderByPayOrder(out_trade_no,trade_no);
//            payLogService.updatePayByOutTradeNo(payLog);
            return "success";

        } else {//验证失败
            return "fail";

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }

    }

    @RequestMapping("orderReceive")
    public String orderReceive() {
        return "home-order-receive";
    }


    /* //退款
     @RequestMapping("toRefund")
     @ResponseBody
     public Result toRefund(String idStr){
         try {
             TbOrderItem orderItem = orderItemService.selectOrderItemById(Long.parseLong(idStr));
             TbOrder order = orderService.selectById(orderItem.getOrderId());
             orderItemService.updateStatusById(Long.parseLong(idStr));
             Map<String,String> map = new HashMap<>();
             map.put("out_trade_no",String.valueOf(order.getPayOrder()));
             map.put("trade_no",order.getAlipayOrder());
             map.put("refund_amount",String.valueOf(orderItem.getTotalFee()));
             map.put("refund_reason","想退款");
             map.put("out_request_no",String.valueOf(idWorker.nextId()));
             return Result.response(ResultEnum.OK).setData(map);
         } catch (Exception e) {
             logger.error("操作异常", e);
             return Result.response(ResultEnum.FAIL);
         }
     }
 */
    @RequestMapping("refund")
    @ResponseBody
    public String refund(String out_trade_no, String trade_no, String refund_amount, String refund_reason, String out_request_no) throws AlipayApiException {
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getGatewayUrl(), alipayConfig.getApp_id(),
                alipayConfig.getMerchant_private_key(), alipayConfig.getFormate(),
                alipayConfig.getCharset(), alipayConfig.getAlipay_public_key(), alipayConfig.getSign_type());

        //设置请求参数
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

        //商户订单号，商户网站订单系统中唯一订单号
        //支付宝交易号
        //请二选一设置
        //需要退款的金额，该金额不能大于订单金额，必填
        //退款的原因说明
        //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"trade_no\":\"" + trade_no + "\","
                + "\"refund_amount\":\"" + refund_amount + "\","
                + "\"refund_reason\":\"" + refund_reason + "\","
                + "\"out_request_no\":\"" + out_request_no + "\"}");

        //请求
        String result = alipayClient.execute(alipayRequest).getBody();

        //输出
        return result;
    }
}
